package net.zjitc.controller;

import net.zjitc.pojo.*;
import net.zjitc.service.CartService;
import net.zjitc.service.CategoryService;
import net.zjitc.service.impl.CartServiceImpl;
import net.zjitc.service.impl.CategoryServiceImpl;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/11.
 */
public class UserCart {
    CartService cartService = new CartServiceImpl();
    CategoryService categoryService = new CategoryServiceImpl();
    @URLMapping(url = "/findMyCart")
    public String findMyCart(HttpServletRequest request, HttpServletResponse response){
        List<Category> clist = categoryService.findAll();
        request.setAttribute("clist",clist);
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            return "/WEB-INF/user/login.jsp";
        }
        List<CartItem> list = cartService.findByUid(user.getUid());
        request.setAttribute("list",list);

        double total = 0.0;
        if(list==null||list.size()==0){return "/WEB-INF/user/cart.jsp";}
        for(CartItem c:list){
            total = total+c.getQuantity()*c.getProduct().getShop_price();
        }
        request.setAttribute("total",total);
        return "/WEB-INF/user/cart.jsp";
    }
    @URLMapping(url = "/addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> map = request.getParameterMap();
        CartItem cartItem = new CartItem();
        Product product = new Product();
        try{
            User user = new User();
            user = (User) request.getSession().getAttribute("user");
            user.setUid(user.getUid());
            BeanUtils.populate(cartItem,map);
            BeanUtils.populate(product,map);
            cartItem.setUser(user);
            cartItem.setProduct(product);
            int count = cartService.add(cartItem);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Redirect:"+request.getContextPath()+"/findMyCart";
    }
    @URLMapping(url = "/removeCart")
    public String removeCart(HttpServletRequest request, HttpServletResponse response) {
        String cartid=request.getParameter("cartid");
        int count=cartService.deletecart(cartid);
        return "Redirect:"+request.getContextPath()+"/findMyCart";
    }
    @URLMapping(url = "/clearCart")
    public String clearCart(HttpServletRequest request, HttpServletResponse response){
        User user= (User) request.getSession().getAttribute("user");
        int count=cartService.clear(user.getUid());
        String url=request.getContextPath()+"/findMyCart";
        return "Redirect:"+url;
    }
}
